<?php
namespace app\console\behavior;
use app\console\model\Base;
use think\facade\Hook;
use think\facade\Request;
use think\Db;
class SinglePic extends Base
{
    /*
     * 写入前上传图片，然后写入后修改到指定目录内
     * 提交按钮才提交数据
     */
    private $controller = null;
    private $class = null;
    private $model = null;

    public function initialize()
    {
        $this->controller = Request::controller(true);
        $this->class = '\app\console\model\\'.Request::controller();
        $this->model = new $this->class;
    }

    /**
     * 用于上传后台图片移动到指定目录和id下
     * @param $data
     * 原movePic
     */
    public function before_write($data,$file_field = 'single_pic')
    {

        if (is_array($data)) {
            $file_field = $data[1];
            $data = $data[0];
        }
        $controller = Request::controller(true);
        try {
            $file = request()->file($file_field);
        } catch (\Exception $e) {
        }

        if (!empty($file)) {

            // 移动到框架应用根目录/uploads/ 目录下
            $info = $file->move('./uploads/'. $controller,savePicName());
            if ($info) {
                $ret =  $info->getFilename();
                if (file_exists('./uploads/' . $this->controller . '/' . $data->single_pic_url)) //
                {

                    $_v = explode('/', substr($data->single_pic_url, 0, -4)); //先去掉后缀在获取原图片路径
                    try {
                        $file_list = scandir('./uploads/' . $this->controller . '/' . $data->id); //如果不存在会抛出E_WARNING
                        krsort($file_list);
//                    array(4) {
//                    [3] => string(59) "20180925152234_fcb551f5f2dfda07fa0414d9fb4fb683_154_144.jpg"
//                    [2] => string(51) "20180925152234_fcb551f5f2dfda07fa0414d9fb4fb683.jpg"
//                    [1] => string(2) ".."
//                    [0] => string(1) "."

                        array_splice($file_list, -2);//-2 意味着从数组的倒数第二个元素开始。
                        foreach ($file_list as $kf => $vf) {
                            $str = substr($vf, 0, -4);
                            if (strpos(substr($vf, 0, -4), $_v[1]) !== false) {
                                unlink('./uploads/' . $this->controller . '/' . $_v[0] . '/' . $vf);
                            }
                        }
                    } catch (\Exception $e) {
                    }

                    //unlink('./uploads/'.$controller.'/' . $v);
                }
            } else {
                // 上传失败获取错误信息
                $ret = $file->getError();
            }



        return $ret;
        }
        return Request::param($file_field.'_url','');
    }

    public function after_write($data,$file_field = 'single_pic')
    {

//        dump($_FILES);
//        dump(\request()->file());
//        dump($data);
//        halt(Request::param());
        if (is_array($data)) {
            $file_field = $data[1];
            $data = $data[0];
        }
        $controller = Request::controller(true);
        $ret = [];
        if(!empty($data->$file_field)){ //不为空，否则,手动删除会报错
                $arr_value = current(explode('/',$data->$file_field));
                if($arr_value != $data->id)
                {
                    (new \FileUtil())->moveFile('uploads/'.$controller.'/'.$data->$file_field,'uploads/'.$controller.'/'.$data->id.'/'.$data->$file_field);
                    $ret = $data->id.'/'.$data->$file_field;

                }else{
                    $ret = $data->$file_field;

                }
                Db::name($controller)->where('id',$data->id)->setField($file_field,$ret);
        }

    }

    public function before_delete($data,$file_field = 'single_pic')
    {

        $sql = "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" . config('database.prefix') . $this->controller . "' AND table_schema = '" . config('database.database') . "' and  COLUMN_NAME = 'parent_id'";
        $ret = Db::query($sql);
        if (empty($ret)) { //如果不存在此列
            $str = $data[0]->id;
        } else {
            $str = sonPath($this->model->select(), $data[0]->id, true);//包含自己的图片
        }
        if (is_array($data)) {
            $file_field = $data[1];
            $data = $data[0];
        }
        $single_pic = $this->model->where('id', 'in', $str)->column("id,{$file_field}");
        foreach ($single_pic as $k => $vv) { //先删除本地图片包含当前类
                if (file_exists('./uploads/' . $this->controller . '/' . $vv)) //
                {
                    $_v = explode('/', substr($vv, 0, -4));//先去掉后缀在获取原图片路径
                    $file_list = scandir('./uploads/' . $this->controller . '/' . $k);
                    krsort($file_list);
//                    array(4) {
//                    [3] => string(59) "20180925152234_fcb551f5f2dfda07fa0414d9fb4fb683_154_144.jpg"
//                    [2] => string(51) "20180925152234_fcb551f5f2dfda07fa0414d9fb4fb683.jpg"
//                    [1] => string(2) ".."
//                    [0] => string(1) "."

                    array_splice($file_list, -2);//-2 意味着从数组的倒数第二个元素开始。
                    foreach ($file_list as $kf => $vf) {
                        $str = substr($vf, 0, -4);
                        if (strpos(substr($vf, 0, -4), $_v[1]) !== false) {
                            unlink('./uploads/' . $this->controller . '/' . $_v[0] . '/' . $vf);
                        }
                    }
                    //unlink('./uploads/'.$controller.'/' . $v);
                }

        }
        $this->model->where('id', 'in', $str)->delete();//在删除数据
    }


}